#include "Component/Item/Light/RoomSwitchComponent.h"

#include "Component/Item/Light/RoomLightComponent.h"
#include "Subsystem/ItemManager/RoomLightManagerSubsystem.h"
#include "Subsystem/RoomManager/RoomManagerFunctionLibrary.h"

void URoomSwitchComponent::BeginPlay()
{
	Super::BeginPlay();

	if (URoomLightManagerSubsystem* RoomLightManagerSubsystem = URoomManagerFunctionLibrary::GetRoomLightManagerSubsystem(this))
	{
		RoomLightManagerSubsystem->RegisterRoomSwitch(GetOwner());
	}
}

void URoomSwitchComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	if (URoomLightManagerSubsystem* RoomLightManagerSubsystem = URoomManagerFunctionLibrary::GetRoomLightManagerSubsystem(this))
	{
		RoomLightManagerSubsystem->UnregisterRoomSwitch(GetOwner());
	}

	Super::EndPlay(EndPlayReason);
}

void URoomSwitchComponent::SetLightSwitch(bool bSwitchOn)
{
	bLightSwitchOn = bSwitchOn;
	UpdateState(false);
}

void URoomSwitchComponent::ToggleLightSwitch()
{
	SetLightSwitch(!bLightSwitchOn);
}

void URoomSwitchComponent::SetElectric(bool bElectric)
{
	bHasElectric = bElectric;
	UpdateState(false);
}

void URoomSwitchComponent::UpdateState(bool bForceUpdate)
{
	if (bLightSwitchOn && bHasElectric)
	{
		if (!bLightOn || bForceUpdate)
		{
			TurnOnLightImp();
		}
	}
	else
	{
		if (bLightOn || bForceUpdate)
		{
			TurnOffLightImp();
		}
	}
}

void URoomSwitchComponent::TurnOnLightImp()
{
	bLightOn = true;
	for (const TObjectPtr<URoomLightComponent> RoomLightComponent : GetRoomLightComponents())
	{
		RoomLightComponent->TurnOnLight(false);
	}
}

void URoomSwitchComponent::TurnOffLightImp()
{
	bLightOn = false;
	for (const TObjectPtr<URoomLightComponent> RoomLightComponent : GetRoomLightComponents())
	{
		RoomLightComponent->TurnOffLight(false);
	}
}

TArray<URoomLightComponent*> URoomSwitchComponent::GetRoomLightComponents()
{
	if (RoomLightComponents.IsEmpty())
	{
		const FName RoomName = URoomManagerFunctionLibrary::GetActorRoomName(this, GetOwner());
		if (URoomLightManagerSubsystem* RoomLightManagerSubsystem = URoomManagerFunctionLibrary::GetRoomLightManagerSubsystem(this))
		{
			RoomLightComponents = RoomLightManagerSubsystem->GetRoomComponents<URoomLightComponent>(RoomName);
		}
	}

	return RoomLightComponents;
}
